/**
 * Created by zycool on 2016/9/6.
 * 作业点维修记录 - 详情 - 涂层维修 - 维修整改 - 腐蚀控制
 */

;(function ($, window, document, undefined) {

    // 地址参数
    var task = {
        id: function(){
            var v = $('#JQ_id').val();
            if(v){
                return v;
            }
            return '';
        }(),
        name: function(){
            var v = $('#JQ_name').val();
            if(v){
                v = eval('"'+v+'"');
                return v;
            }
            return '';
        }(),
        code: function(){
            var v = $('#JQ_code').val();
            if(v){
                v = eval('"'+v+'"');
                return v;
            }
            return '';
        }(),
        pipe: function(){
            var v = $('#JQ_pipe').val();
            if(v){
                v = eval('"'+v+'"');
                return v;
            }
            return '';
        }()
    };

    // 已被转化的图片数量
    var count = 0;
    // 作业点图片总数量
    var work_pic = [];

    // 记录数据模板
    var repairWork = [
        {
            key: 'START_NODE', value: '管沟开挖', node: [
            {name: 'buriedDepth', title: '埋深(m)'},
            {name: 'depth', title: '深度(m)'},
            {name: 'difficultToRepair', title: '是否难以维修'},
            {name: 'length', title: '长度(m)'},
            {name: 'width', title: '宽度(m)'},
            {name: 'remark', title: '备注'},
            {name: 'imgList', title: '照片'}
        ]
        },
        {
            key: 'CORROSION_ENVIRONMENT_NODE', value: '腐蚀环境调查', node: [
            {name: 'deepRootedPlants', title: '根系植物'},
            {name: 'groundwater', title: '地下水'},
            {name: 'soilColor', title: '土壤颜色'},
            {name: 'soilCompactness', title: '土壤松紧度'},
            {name: 'soilHumidity', title: '土壤干湿度'},
            {name: 'soilLayer', title: '土壤分层描述'},
            {name: 'soilParticlesGroup', title: '土壤颗粒组划分'},
            {name: 'soilPh', title: 'PH值'},
            {name: 'soilResistivity', title: '土壤电阻率(Ω▪m)'},
            {name: 'soilSamplingNumber', title: '土壤取样编号'},
            {name: 'terrainGeomorphology', title: '地形地貌描述'},
            {name: 'remark', title: '备注'},
            {name: 'imgList', title: '照片'}
        ]
        },
        {
            key: 'CTRL_LEAKAGE_POINT_NODE', value: '漏损点测量', node: [
            {name: 'maxLength', title: '最大漏损点长度(mm)'},
            {name: 'maxWidth', title: '最大漏损点宽度(mm)'},
            {name: 'clock', title: '时钟位置(h:min)'},
            {name: 'description', title: '漏损点外观描述'},
            {name: 'remarks', title: '备注'},
            {name: 'imgList', title: '照片'}
        ]
        },
        {
            key: 'COAT_SURVEY_NODE', value: '防腐层调查', node: [
            {name: 'appearance', title: '外观质量'},
            {name: 'coatingMaterial', title: '防腐层类型'},
            {name: 'coatingThicknessTest1', title: '剥离强度(N/cm)-测试1'},
            {name: 'coatingThicknessTest2', title: '剥离强度(N/cm)-测试2'},
            {name: 'coatingThicknessTest3', title: '剥离强度(N/cm)-测试3'},
            {name: 'coatingThicknessTest4', title: '剥离强度(N/cm)-测试4'},
            {name: 'electricSparkAmount', title: '电火花检测-漏点数'},
            {name: 'electricSparkTestVoltage', title: '电火花检测-检查电压（KV）'},
            {name: 'peelingStrengthTest1', title: '厚度(mm)-测试1'},
            {name: 'peelingStrengthTest2', title: '厚度(mm)-测试2'},
            {name: 'peelingStrengthTest3', title: '厚度(mm)-测试3'},
            {name: 'peelingStrengthTest4', title: '厚度(mm)-测试4'},
            {name: 'pipeBodyTemperature', title: '管体温度(℃)'},
            {name: 'remark', title: '备注'},
            {name: 'imgList', title: '照片'}
        ]
        },
        {
            key: 'SURFACE_TREATMENT_NODE', value: '表面处理', node: [
            {name: 'anchorDepth', title: '锚纹深度(mm)'},
            {name: 'derustingGrade', title: '除锈等级'},
            {name: 'remark', title: '备注'},
            {name: 'imgList', title: '照片'}
        ]
        },
        {
            key: 'CP_SURVEY_NODE', value: '阴保调查', node: [
            {name: 'acPotential', title: '交流干扰电压(V)'},
            {name: 'freeCorrosionPotential', title: '自然电位(-mV)'},
            {name: 'maxPotential', title: '直流干扰-最大值(mV)'},
            {name: 'minPotential', title: '直流干扰-最小值(mV)'},
            {name: 'onPotential', title: '通电电位(-mV)'},
            {name: 'polarizedPotential', title: '极化电位(-mV)'},
            {name: 'soilResistivity', title: '土壤电阻率(Ω▪m)'},
            {name: 'remark', title: '备注'},
            {name: 'imgList', title: '照片'}
        ]
        },
        {
            key: 'DEFECT_MEASURE_NODE', value: '缺陷测量', node: [
            {name: 'actualClock', title: '实测 时钟位置'},
            {name: 'actualFeatureType', title: '实测缺陷类型'},
            {name: 'actualLength', title: '实测 长(mm)'},
            {name: 'actualWidth', title: '实测 宽(mm)'},
            {name: 'actualX', title: '实测经度(°)'},
            {name: 'actualY', title: '实测纬度(°)'},
            {name: 'actualZ', title: '实测高度(°)'},
            {name: 'clock', title: '时钟位置(h:min)'},
            {name: 'defectDescription', title: '实测 缺陷描述'},
            {name: 'defectNumber', title: '缺陷编号'},
            {name: 'featureSubType', title: '缺陷子类型'},
            {name: 'featureType', title: '缺陷类型'},
            {name: 'length', title: '长(mm)'},
            {name: 'width', title: '宽(mm)'},
            {name: 'mileage', title: '绝对距离(m)'},
            {name: 'ndtReportNumber', title: '无损检测报告编号'},
            {name: 'planRepairMethod', title: '评价修复方法'},
            {name: 'repairMethod', title: '变更修复方法'},
            {name: 'repairRemark', title: '变更修复方法原因'},
            {name: 'repairWorkload', title: '工作量(㎡)'},
            {name: 'imgList', title: '照片'}
        ]
        },
        {
            key: 'REPAIR_NODE', value: '缺陷修复', node: [
            {name: 'manufacturer', title: '生产厂商'},
            {name: 'material', title: '材质'},
            {name: 'length', title: '套筒尺寸-长度(mm)'},
            {name: 'wallThickness', title: '套筒尺寸-壁厚(mm)'},
            {name: 'od', title: '套筒尺寸-外径(mm)'},
            {name: 'perfusionProcess', title: '灌注工艺'},
            {name: 'repairLength', title: '修复长度(mm)'},
            {name: 'socketStructure', title: '套筒结构'},
            {name: 'surfaceTemperature', title: '管表温度(℃)'},
            {name: 'environmentalTemperature', title: '环境温度(℃)'},
            {name: 'weldingGrade', title: '焊材牌号'},
            {name: 'weldingMethod', title: '焊接方法'},
            {name: 'workload', title: '工作量(㎡)'},
            {name: 'remark', title: '备注'},
            {name: 'imgList', title: '照片'}
        ]
        },
        {
            key: 'COAT_REPAIR_NODE', value: '防腐层修复', node: [
            {name: 'edmLeak', title: '电火花检漏(电压KV)'},
            {name: 'environmentalTemperature', title: '环境温度(℃)'},
            {name: 'isJoint', title: '是否为补口'},
            {name: 'materialManufacturer', title: '修复材料厂商'},
            {name: 'repairLength', title: '修复长度(mm)'},
            {name: 'repairMaterial', title: '修复材料'},
            {name: 'repairThickness', title: '修复厚度(mm)'},
            {name: 'surfaceTemperature', title: '管表温度(℃)'},
            {name: 'workload', title: '工作量(㎡)'},
            {name: 'remark', title: '备注'},
            {name: 'imgList', title: '照片'}
        ]
        },
        {
            key: 'END_NODE', value: '管沟回填', node: [
            {name: 'remark', title: '备注'},
            {name: 'imgList', title: '照片'}
        ]
        }
    ];

    // 加载详情
    if (task.id) {
        var $div = $('#JQ_all_work_record');
        var url = DyyBase.root_path + '/corrctrl/repairMgr/queryRepairNode.json';
        DyyBase.ajax(url, {defectId: task.id}, function (dataset) {
            if(dataset.bool){
                var data = dataset.result;
                for (var i = 0, len = data.length; i < len; i++) {
                    var $line = $('<div class="zy-record-line zy-pdf-area"></div>');
                    var span = '', div = '';
                    for (var j = 0, lens = repairWork.length; j < lens; j++) {
                        if (data[i].hasOwnProperty(repairWork[j]['key'])) {
                            if(data[i][repairWork[j]['key']]){
                                data[i][repairWork[j]['key']] = DyyBase.clearNull(data[i][repairWork[j]['key']]);
                                var meta = '<div class="zy-record-meta l"><span>' + repairWork[j]['value'] + '</span></div>';
                                var info = '';
                                if (repairWork[j].hasOwnProperty('node')) {
                                    for (var n = 0, lenth = repairWork[j]['node'].length; n < lenth; n++) {
                                        if (data[i][repairWork[j]['key']].hasOwnProperty(repairWork[j]['node'][n]['name'])) {
                                            if (repairWork[j]['node'][n]['name'] === 'imgList') {
                                                var img = '';
                                                if (data[i][repairWork[j]['key']].hasOwnProperty('imgList')) {
                                                    if(data[i][repairWork[j]['key']]['imgList']){
                                                        if (data[i][repairWork[j]['key']]['imgList'].hasOwnProperty('ALL')) {
                                                            if(data[i][repairWork[j]['key']]['imgList']['ALL'] && data[i][repairWork[j]['key']]['imgList']['ALL'].length){
                                                                for (var m = 0, lenths = data[i][repairWork[j]['key']]['imgList']['ALL'].length; m < lenths; m++) {
                                                                    img += '<span><a target="_blank" href="'+DyyBase.file_path + data[i][repairWork[j]['key']]['imgList']['ALL'][m]['path']+'"><img crossorigin="anonymous" src="' + DyyBase.file_path + data[i][repairWork[j]['key']]['imgList']['ALL'][m]['path'] + '" onload="storeImage(this)" /></a></span>';
                                                                }
                                                            }
                                                        } else if (data[i][repairWork[j]['key']]['imgList'].hasOwnProperty('REPAIR_BEFORE')) {
                                                            if(data[i][repairWork[j]['key']]['imgList']['REPAIR_BEFORE'] && data[i][repairWork[j]['key']]['imgList']['REPAIR_BEFORE'].length){
                                                                for (var x = 0, len_x = data[i][repairWork[j]['key']]['imgList']['REPAIR_BEFORE'].length; x < len_x; x++) {
                                                                    img += '<span><a target="_blank" href="'+DyyBase.file_path + data[i][repairWork[j]['key']]['imgList']['REPAIR_BEFORE'][x]['path']+'"><img crossorigin="anonymous" src="' + DyyBase.file_path + data[i][repairWork[j]['key']]['imgList']['REPAIR_BEFORE'][x]['path'] + '" onload="storeImage(this)" /></a></span>';
                                                                }
                                                            }
                                                        } else if (data[i][repairWork[j]['key']]['imgList'].hasOwnProperty('REPAIR_DURING')) {
                                                            if(data[i][repairWork[j]['key']]['imgList']['REPAIR_DURING'] && data[i][repairWork[j]['key']]['imgList']['REPAIR_DURING'].length){
                                                                for (var y = 0, len_y = data[i][repairWork[j]['key']]['imgList']['REPAIR_DURING'].length; y < len_y; y++) {
                                                                    img += '<span><a target="_blank" href="'+DyyBase.file_path + data[i][repairWork[j]['key']]['imgList']['REPAIR_DURING'][y]['path']+'"><img crossorigin="anonymous" src="' + DyyBase.file_path + data[i][repairWork[j]['key']]['imgList']['REPAIR_DURING'][y]['path'] + '" onload="storeImage(this)" /></a></span>';
                                                                }
                                                            }
                                                        } else if (data[i][repairWork[j]['key']]['imgList'].hasOwnProperty('REPAIR_AFTER')) {
                                                            if(data[i][repairWork[j]['key']]['imgList']['REPAIR_AFTER'] && data[i][repairWork[j]['key']]['imgList']['REPAIR_AFTER'].length){
                                                                for (var z = 0, len_z = data[i][repairWork[j]['key']]['imgList']['REPAIR_AFTER'].length; z < len_z; z++) {
                                                                    img += '<span><a target="_blank" href="'+DyyBase.file_path + data[i][repairWork[j]['key']]['imgList']['REPAIR_AFTER'][z]['path']+'"><img crossorigin="anonymous" src="' + DyyBase.file_path + data[i][repairWork[j]['key']]['imgList']['REPAIR_AFTER'][z]['path'] + '" onload="storeImage(this)" /></a></span>';
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                                div += '<div class="zy-record-img"><label>现<br>场<br>照<br>片</label>' + img + '</div>';
                                            } else {
                                                span += '<span title="'+repairWork[j]['node'][n]['title']+'：'+data[i][repairWork[j]['key']][repairWork[j]['node'][n]['name']]+'">' + repairWork[j]['node'][n]['title'] + '：<em>' + data[i][repairWork[j]['key']][repairWork[j]['node'][n]['name']] + '</em></span>';
                                            }
                                        }
                                    }
                                }
                                info = meta + '<div class="zy-record-body l"><div class="zy-record-info">' + span + '</div>' + div + '</div>';
                                $line.append(info).append('<div class="clear"></div>');
                            }
                        }
                    }
                    if($line.html()){
                        $div.append($line);
                    }
                }
            }
        });
    }

    // 返回列表
    $('#JQ_goback_list').click(function () {
        window.location.href = DyyBase.root_path + '/corrctrl/CoatRepairTask/init.html';
    });

    // 返回详情
    $('#JQ_goback_details').click(function () {
        window.history.go(-1);
    });

    // 将图片临时存储
    window.storeImage = function (img) {
        work_pic.push(img);
    };

    // 导出pdf操作
    function exportPDF() {
        DyyBase.isLogin(function () {
            $(this).EXPT({
                type: 'name',
                name: task.pipe + task.name + task.code + '作业点维修记录',
                yesBtnAct: function (callback, fname) {
                    callback();
                    canvasPdf.exportHtmlPdf({
                        dom: $('#JQ_all_work_record'),
                        server: DyyBase.root_path + '/comm/downImgPdf.json',
                        param: {
                            fileName: fname,
                            name: task.name + task.code + '作业点维修记录'
                        }
                    });
                }
            });
        });
    }

    // 将图片base64转码
    function imgBase64(pics) {
        if (pics[count]) {
            try {
                var canvas = document.createElement('canvas');
                canvas.width = 110;
                canvas.height = 95;
                var ctx = canvas.getContext('2d');
                ctx.drawImage(pics[count], 0, 0, 110, 95);
                var ext = pics[count].src.substring(pics[count].src.lastIndexOf('.') + 1).toLowerCase();
                var dataURL = canvas.toDataURL('image/' + ext);
                pics[count].src = dataURL;
                pics[count].removeAttribute('onload');
                pics[count].removeAttribute('crossorigin');
                count++;
                if (pics[count]) {
                    imgBase64(pics);
                } else {
                    if (count === work_pic.length) {
                        exportPDF();
                    }
                }
            } catch (e) {
                throw new Error(e.message);
            }
        }
    }

    // 导出pdf
    $('#JQ_export_pdf').click(function () {

        if (count == 0 && work_pic.length > 0) {
            imgBase64(work_pic);
        } else {
            exportPDF();
        }

    });

})(jQuery, window, document);